package com.blade.controller;

import com.blade.common.utils.StaticResourceUtil;
import com.blade.vo.ReturnJsonVO;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/common-upload")
public class FileUploadController {
    @ResponseBody
    @RequestMapping(value = "/upload-file", method = RequestMethod.POST, produces = MediaType.TEXT_HTML_VALUE)
    public String uploadFile(MultipartFile uploadFile, String key) {
        Map<String, String> fileInfo = new HashMap<>();
        fileInfo.put("fileName", upload(uploadFile, StaticResourceUtil.getResourceUploadPath(key)));

        return ReturnJsonVO.getReturnJsonVo(ReturnJsonVO.SUCCESS, null, fileInfo).toJSONString();
    }

    /**
     * 开始上传文件
     * @param uploadFile 上传的文件
     * @param uploadPath 文件上传保存路径
     * @return
     */
    private String upload(MultipartFile uploadFile, String uploadPath) {
        String originalFilename = uploadFile.getOriginalFilename();
        String fileName = new Date().getTime() + originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
        File targetFile = new File(uploadPath, fileName);

        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            uploadFile.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileName;
    }
}
